package code.starivan.leetcode;

/**
 * Created by Ivan on 2015/10/27.
 */

/*
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

        For example:

        Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

        Note:
        The order of the result is not important. So in the above example, [5, 3] is also correct.
        Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
        Credits:
        Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/

public class N260_SingleNumberIII {

    public static void  test(){
        int[] nums=new int[]{1, 2, 1, 3, 2, 5};
        int[] ret=new N260_SingleNumberIII().singleNumber(nums);
        for(int i=0;i<ret.length;++i){
            System.out.print(ret[i]+" ");
        }
    }

    public int[] singleNumber(int[] nums) {
        if(nums==null||nums.length<2){
            return new int[0];
        }

        int xor=nums[0];
        for(int i=1;i<nums.length;++i){
            xor=xor^nums[i];
        }

        int[] ret=new int[2];
        int lowbit=xor&(-xor);
        for(int i=0;i<nums.length;++i){
            if((lowbit&nums[i])!=0){
                ret[0]^=nums[i];
            }else{
                ret[1]^=nums[i];
            }
        }

        return ret;
    }
}
